<template>
  <div class="app-container">
    <el-card>
      <el-row :gutter="20" align="middle">
        <el-col :span="24" class="input-button-group">
          <el-select v-model="statusId" placeholder="选择状态" clearable>
            <el-option :value="9" label="已读" />
            <el-option :value="10" label="未读" />
          </el-select>

          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
          />
          <el-button icon="el-icon-search" @click="handleSearch">筛选</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      stripe
      height="532"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="100" sortable :sort-by="sortById">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>

      <el-table-column label="内容" width="210" align="center">
        <template slot-scope="scope">
          {{ scope.row.content }}
        </template>
      </el-table-column>

      <el-table-column label="发件人" width="170" align="center">
        <template slot-scope="scope">
          {{ scope.row.ownerName }}
        </template>
      </el-table-column>

      <el-table-column label="电话" width="170" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>

      <el-table-column label="状态" width="227" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.statusId"
            :active-color="'#13ce66'"
            :inactive-color="'#ff4949'"
            :active-value="9"
            :inactive-value="10"
            active-text="已读"
            inactive-text="未读"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="发件时间" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>

      <!-- Actions Column -->
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="block" style="text-align: center;">
      <el-pagination
        :current-page="page"
        :page-sizes="[9, 20, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getList, updateRow, deleteRow } from '@/api/mailbox'
import { parseTime } from '@/utils/index'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      page: 1,
      pageSize: 9,
      statusId: '',
      dateRange: [],
      total: 0,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '本周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            const day = start.getDay()
            const diff = start.getDate() - day + (day === 0 ? -6 : 1) // 调整为周一
            start.setDate(diff)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleStatusChange(row) {
      const updateData = {
        id: row.id,
        statusId: row.statusId
      }

      updateRow(updateData)
        .then(() => {
          this.$message.success('状态更新成功')
        })
    },
    fetchData() {
      this.listLoading = true

      const beginTime = (Array.isArray(this.dateRange) && this.dateRange.length > 0)
        ? parseTime(this.dateRange[0], '{y}-{m}-{d} {h}:{i}:{s}')
        : null
      const endTime = (Array.isArray(this.dateRange) && this.dateRange.length > 0)
        ? parseTime(this.dateRange[1], '{y}-{m}-{d} {h}:{i}:{s}')
        : null

      getList({
        page: this.page,
        pageSize: this.pageSize,
        content: this.content,
        statusId: this.statusId,
        beginTime,
        endTime
      })
        .then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
    },
    sortById(a, b) {
      return a.id - b.id
    },
    handleSearch() {
      this.page = 1
      this.fetchData()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.fetchData()
    },
    handleCurrentChange(page) {
      this.page = page
      this.fetchData()
    },
    handleDelete(rowId) {
      const ids = [rowId]
      this.$confirm('确定删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRow(ids).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      }).catch(() => {
        this.$message('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.input-button-group {
  display: flex;
  align-items: center;
}

.input-button-group .el-input {
  flex: 1;
  margin-right: 10px;
}
</style>
